package ano.it.service.impl;

import ano.it.dao.PermissionDao;
import ano.it.dao.RoleDao;
import ano.it.dao.UserDao;
import ano.it.entity.PageResult;
import ano.it.entity.QueryPageBean;
import ano.it.pojo.GreenHouse;
import ano.it.pojo.Permission;
import ano.it.pojo.Role;
import ano.it.pojo.User;
import ano.it.service.UserService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Transactional
@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    @Override
    public User findByUsername(String username) {
        User user=userDao.findByUsername(username);
        if(user==null){
            return null;
        }
        Integer userId = user.getId();
        Set<Role> roles=roleDao.findByUserId(userId);
        user.setRoles(roles);
        for (Role role : roles) {
            Integer roleId = role.getId();
            Set<Permission> permissions=permissionDao.findByRoleId(roleId);
            role.setPermissions(permissions);
        }
        return user;
    }

    @Override
    public void addPermission(Integer[] roleIds, Integer userId) {
        for (Integer roleId : roleIds) {
            Map<String,Integer> map=new HashMap<>();
            map.put("roleId",roleId);
            map.put("userId",userId);
            userDao.addPermission(map);
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<GreenHouse> page=userDao.selectByCondition(queryPageBean.getQueryString());
        long total=page.getTotal();
        List<GreenHouse> rows=page.getResult();
        return new PageResult(total,rows);
    }

    @Override
    public void add(User user) {

        userDao.add(user);
    }
}
